package com.bw.controller;

import com.bw.bean.City;
import com.bw.bean.Region;
import com.bw.bean.Trading;
import com.bw.service.RegionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class RegionController {

    @Resource
    private RegionService regionService;

    @RequestMapping("list")
    private String list(Region region, Model model){
        //初始化分页
        PageHelper.startPage(region.getPageNum(),region.getPageSize());
        List<Region> list = regionService.list(region);
        PageInfo<Region> pageInfo = new PageInfo<>(list);
        model.addAttribute("region",region);
        model.addAttribute("list",list);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

    /**
     * 进入添加页面
     */
    @RequestMapping("toadd")
    public String toadd(int rid,Model model){
        if(rid != 0){//如果id！=0，说明是修改，要进行回显。
            Region region = regionService.getById(rid);
            model.addAttribute("region",region);
        }
        model.addAttribute("rid",rid);//回显id
        return "add";
    }

    /**
     * 添加方法
     * tids  逗号分隔的复选框id
     * @return
     */
    @RequestMapping("add")
    public String add(Region region, MultipartFile file,String tids){
        //获取到文件的真实名称
        String filename = file.getOriginalFilename();
        //获取后缀
        String affix = filename.substring(filename.lastIndexOf("."));
        //用UUID生成随机唯一文件名，防止重复
        String savename= UUID.randomUUID().toString()+affix;
        try {
            //保存图片
            file.transferTo(new File("D:\\myupload\\"+savename));
            System.out.println("图片访问路径："+"/myupload/"+savename);
            //把图片访问路径，存入对象，方便插入到数据库
            region.setImmg("/myupload/"+savename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        regionService.save(region,tids);
        return "redirect:list.do";
    }
    /**
     * 省市县三级联动查询
     * @return
     */
    @RequestMapping("getByPid")
    @ResponseBody
    public List<City> getByPid(int pid){
        return regionService.getByPid(pid);
    }
    /**
     * 第4级联动，根据县id，查询复选框
     * @return
     */
    @RequestMapping("getTradings")
    @ResponseBody
    public List<Trading> getTradings(int xid){
        return regionService.getTradings(xid);
    }
}
